package cn.lg.soar.core.aspect;

import cn.lg.soar.common.util.hardware.SystemUtils;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;

/**
 * Spring el 表达式解析工具
 * @author luguoxiang
 * @date 2022/3/29
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class SpelExpressionUtils {

    protected static final Logger LOGGER = LoggerFactory.getLogger(SpelExpressionUtils.class);

    private final static ExpressionParser PARSER = new SpelExpressionParser();

    private final static Cache<String, Expression> CACHE;

    static {
        long l = SystemUtils.TOTAL >> 16;
        CACHE = Caffeine.newBuilder()
                .maximumSize(l)
                .initialCapacity(64)
                .build();
        LOGGER.info("Spel Expression cache max size " + l);
    }

    public static Expression getExpression(String template) {
        return CACHE.get(template, PARSER::parseExpression);
    }

    public static <T>T getValue(String template, EvaluationContext context, Class<T> tClass) {
        return CACHE.get(template, PARSER::parseExpression).getValue(context, tClass);
    }

    public static Object getValue(String template, EvaluationContext context) {
        return CACHE.get(template, PARSER::parseExpression).getValue(context);
    }

}
